package com.joey.concurrency.example.lock;

import com.joey.concurrency.annotation.ThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Author hyy
 **/
@Slf4j
@ThreadSafe
public class ReentrantReadWriteLockExample {

    class Data{}

    public final Map<String, Data> map = new TreeMap<>();
    public final ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
    public final Lock readLock = reentrantReadWriteLock.readLock();
    public final Lock writeLock = reentrantReadWriteLock.writeLock();

    public Data getData(String key){
        readLock.lock();
        try{
            return map.get(key);
        }finally {
            readLock.unlock();
        }
    }

    public void setData(String key,Data data){
        writeLock.lock();
        try{
            map.put(key,data);
        }finally {
            writeLock.unlock();
        }
    }

    public Set<String> getAllKeys(){
        readLock.lock();
        try{
            return map.keySet();
        }finally {
            readLock.unlock();
        }

    }


}
